package ufo.server

import api.action.{BeingAction, Walk, FireWeapon}
import api.event.{BeingDies, BeingPerformedAction, BeingMoved, BeingInjured}
import java.util.UUID
import api.common.{Position, Direction}
import domain.Being
class ServerBeing(id : UUID, val controlledBy : Client, initialPosition : Position, maxHitPoints : Int)(implicit world : World) extends Being(id, initialPosition, maxHitPoints) {
  var maxActionPoints = 5
  var actionPoints = maxActionPoints
  var weapon : Weapon = new Rifle()
	
  def perform(action : BeingAction) = {
	  if (hitPoints == 0) {
		  throw IllegalActionException("Dead!")
	  }

    def doIt(action : BeingAction) = action match {
      case Walk(id, direction) => walk(direction)
      case FireWeapon(id, position) => weapon.fire(position)
    }
    if (actionPoints < action.actionPoints()) {
      throw IllegalActionException("Not enough action points")
    }
    doIt(action)
    actionPoints -= action.actionPoints()
    controlledBy.notify(BeingPerformedAction(id, action, actionPoints))
  }

  def walk(direction : Direction) = {
	  val nextPosition = position.move(direction)
    world.validate(nextPosition)
    position = nextPosition
    world.notify(BeingMoved(id, nextPosition))
  }

  def beginTurn() = {
    actionPoints = maxActionPoints
    // XXX: notify client?
  }

  def injure(damage : Int) = {
	  if (hitPoints == 0) {
		  world.notify(BeingInjured(id, 0))
	  } else {
		  hitPoints -= damage

		  if (hitPoints < 1) {
				hitPoints = 0
				world.notify(BeingDies(id))
	    } else {
			  world.notify(BeingInjured(id, damage))
		  }
	  }
  }
}